<style lang="scss">
.fox-form-template {
  //--fox-form-template-columns: repeat(8, 1fr);
  .form-slot-actions {
    margin-top: 10px;
  }
  .table-like-arr__ck {
    width: 0;
    opacity: 0;
  }
  .el-input-number--small {
    width: auto;
  }
}
.table-like-arr {
  --table-like-arr__tr-padding:  10px 0;
  --table-like-arr__th-width: 60px;
  --table-like-arr__action-width: 120px;
  --table-like-arr__grid-gap: 10px;
  .z-form__array-con0.arr {
    .zform__arr__del-action {
      display: none;
    }
  }
  //--column-width: var(--fox-form-template-columns);
  --table-like-arr__grid-column: var(--table-like-arr__th-width) var(--table-like-arr__column-width) var(--table-like-arr__action-width);
  .z-form__array-con {
    display: grid;
    grid-template-columns: var(--table-like-arr__grid-column);
    grid-gap: var(--table-like-arr__grid-gap);
    .el-form-item__label {
      display: none;
    }
    //.zform__arr_action {
    //  display: none;
    //}
    border-bottom: 1px solid #eee;
    padding: var(--table-like-arr__tr-padding);
  }
  .zform__arr__add-action {
    margin-top: 10px;
  }
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
  .form-arr-header {
    display: grid;
    grid-template-columns: var(--table-like-arr__grid-column);
    grid-gap: var(--table-like-arr__grid-gap);
    border: 1px solid #eee;
    border-left: none;
    border-right: none;
    padding: var(--table-like-arr__tr-padding);
  }
  .table-like-arr__th {
    display: grid;
    grid-template-columns: 30px 30px;
    align-items: center;

  }
}
</style>


<template>
  <div class="fox-form-template"
  :style="styleObj"
  >
    <z-space vertical>
<!--      <div>-->
<!--        &lt;!&ndash;        <el-button @click="importData">导入</el-button>&ndash;&gt;-->
<!--        <el-button v-if="showCh()" @click="clearAll">清除</el-button>-->
<!--        &lt;!&ndash;        <el-button @click="getUUIDS">获取UUIDS</el-button>&ndash;&gt;-->
<!--      </div>-->
      <div class="fox-form-template__con">
        <z-form-template
            :slots="search.slots"
            :def="search.def"
            :custom-def="search.customDef"
            ref="searchForm"
            @fire="search.onFire"
            @ready="onReady"
            v-bind="formConfig"
        >
<!--          <template #array_beforebegin="form_scope">-->
<!--            <el-button style="margin-bottom: 10px;" @click="clearAll">清除</el-button>-->
<!--          </template>-->
        </z-form-template>
      </div>
    </z-space>
  </div>
</template>

<script>

import FormArrHeader from "./FormArrHeader";
import FormCheckedAll from "./FormCheckedAll";
import FormCheckedTr from "./FormCheckedTr";

function createDefaultFormSlot() {
  return `
<div class="form-slot-actions" v-if="scope.level === 1">
  <el-button class="fox-form__add" type="primary" @click="zform__callEvent('form-submit', scope, $event)"">保存</el-button>
  <el-button class="fox-form__edit" type="primary" @click="zform__callEvent('form-submit', {...scope, IS_EDIT: true}, $event)"">保存</el-button>
  <el-button class="fox-form__reset" @click="zform__reset(scope, $event)"">重置</el-button>
</div>
  `
}


export default {
  name: 'FoxFormTemplate',
  components: {},
  data() {
    return {
    }
  },
  props: {
    properties: {
      type: Object,
      default() {
        return {}
      }
    },
    formConfig: {
      type: Object,
      default() {
        return {}
      }
    },
    handleProp: null
  },
  computed: {
    styleObj() {
      return {}
    }
  },
  setup(props, outerCtx) {
    const {reactive} = globalThis.vueCompositionAPI;
    let formCtx = null;
    let state = reactive({
      checkedCities: []
    })

    CustomCusComponent.registerOnce(FormArrHeader);
    CustomCusComponent.registerOnce(FormCheckedAll);
    CustomCusComponent.registerOnce(FormCheckedTr);

    let zformCtx = null
    let form_aa_ctx = null


    function handleProps() {
      let o = ZY.JSON5.parse(ZY.JSON5.stringify( props.properties))
      ZY.lodash.each(o, function (item, key) {
        if (item.type === 'array') {
          // console.log(item.items)
          let k = Object.keys( item.items.properties)
          if (!item.ui) {
            item.ui = {}
          }
          ZY.lodash.each(item.items.properties, function (arrItem, arrItemKey) {
            if (props.handleProp) {
              props.handleProp(arrItem, arrItemKey)
            }
          })
          item.ui.class = [
            'table-like-arr',
          ]
          item.ui.attrs = [
            [
              'style',
              `--table-like-arr__column-width: repeat(${k.length}, 1fr)`,
            ],
          ]
        }
      })
      return o
    }

    function deepSetModel(model = {}) {
      ZY.lodash.each(model, function (item, key) {
        if (Array.isArray(item)) {
          item.forEach(v => {
            deepSetModel(v)
          })
        }
        else if (ZY.lodash.isObject(item)) {
          deepSetModel(item)
        }
        else {
          if (typeof item === 'undefined') {
            model[key] = null
          }
        }
      });
      return model
    }

    let search =  {
      slots: {
        array_con_afterbegin: `<form-checked-tr :scope="scope"></form-checked-tr>`,
        array_afterbegin: `<form-checked-all :scope="scope"></form-checked-all>`,
        // array_afterbegin2: `<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">`,
        // array_aftereend: `</el-checkbox-group>`,
        object_beforeend: createDefaultFormSlot()
      },
      customDef: {
        data() {
          return {
            // checkAll: false,
            checkedCities: [],
            // cities: [],
            scope: null,
            mitt: ZY_EXT.mitt(),
            // isIndeterminate: true
          }
        },
        created() {
          zformCtx = this
        },
        watch: {
          checkedCities: {
            handler(newVal) {
              // console.log('newVal', newVal)
              state.checkedCities = newVal
            },
            deep: true
          }
        },
        provide() {
          let self = this
          return {
            form_aaa: {
              mitt: self.mitt,
              checkedCities: self.checkedCities,
              setCheck(v, scope) {
                self.checkedCities = v
                // console.log(scope)
                self.scope = scope
              },
              getCheck() {
                return self.checkedCities
              },
              setCheckByIndex(index, v, scope) {
                if (!v) {
                  self.checkedCities.splice(index, 1)
                } else {
                  // self.checkedCities[index] = v
                  self.$set(self.checkedCities, index, v)
                }
                self.scope = scope
                // state.checkedCities =  this.checkedCities
                // console.log('setCheckByIndex',  index, v,  this.checkedCities, state.checkedCities )
              },
              reload() {
                form_aa_ctx = this
                // console.log('chaneg')
                state.checkedCities = this.checkedCities
              },
            }
          }
        },
        methods: {
          arrChange(type, {index} = {}) {
            // console.log('arrChange', index)
            if (type === 'delete') {
              this.checkedCities.splice(index, 1)
              state.checkedCities =  this.checkedCities
            }
            this.$nextTick(() => {
              this.mitt.emit('arr-change', {
              })
            })
          }
        }
      },
      def: {
        ui: {
          attrs: Object.entries({
          })
        },
        properties: handleProps(),
      },
      onFire([type, args, ctx] = []) {
        // console.log('type', type)
        if (type === 'form-submit') {
          let {parts, partName} = args.scope
          let model = parts[partName].model


          let newModel = deepSetModel(model)
          console.log('form-submit', newModel, args.scope)
          outerCtx.emit('form-submit', newModel, args.scope)
        }
      }
    }


    function onReady(e) {
      formCtx = e;
      // e.form.resetFields()
      outerCtx.emit('form-ready', e)
    }

    function clearAll() {
      // console.log(formCtx, zformCtx)
      form_aa_ctx.checkedCities = []
      state.checkedCities = []
      zformCtx.mitt.emit('clear-all')
    }

    function showCh() {
      // if (zformCtx) {
      //   console.log('zformCtx', state.a, zformCtx.checkedCities)
      //   return zformCtx.checkedCities.length > 0
      // }
      // return false
      // console.log('sdsdsdsdsdsds')
      return state.checkedCities.length > 0
    }

    function getUUIDS() {
      // console.log( state.checkedCities)
      let items = zformCtx?.scope?.items ?? []
      let  indexArr = new Map()
      state.checkedCities.forEach((item, index) => {
        if (item) {
          indexArr.set(index, 'hello')
        }
      })
      // console.log(indexArr, items)
    }

    function importData(data = {}) {
      // console.log(formCtx)
      // {
      //   text: '111',
      //       maxText: '1111',
      //     arr: [
      //   {
      //     text: '111'
      //   }
      // ]
      // }
      setTimeout(() => {
        formCtx.form.importData(data)
      }, 30)
    }

    // console.log(props)

    return {
      importData,
      onReady,
      getUUIDS,
      showCh,
      clearAll,
      search,
      state,
    }
  }
}
</script>
